<!--  线 + 柱混合图 -->
<template>
  <el-card style="height: 1000px;">
    <template #header>
      <div class="flex-x-between">
        <div class="flex-y-center">
          访问趋势
          <el-tooltip effect="dark" content="点击试试下载" placement="bottom">
            <i-ep-download class="cursor-pointer hover:color-#409eff ml-1" @click="handleDownloadChart" />
          </el-tooltip>
        </div>
      </div>
    </template>

    <el-row :gutter="10">
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card>
          <VueEchart style="width:100%;height: 400px" :option="options" ref="echart"></VueEchart>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card>
          <VueEchart style="width:100%;height: 400px" :option="option2" ref="echart"></VueEchart>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 30px;">
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card>
          <VueEchart style="width:100%;height: 400px" :option="option3" ref="echart"></VueEchart>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card>
          <VueEchart style="width:100%;height: 400px" :option="option4" ref="echart"></VueEchart>
        </el-card>
      </el-col>
    </el-row>
    <div :id="id" :class="className" :style="{ height, width }"></div>
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import StatsAPI, { VisitTrendVO, VisitTrendQuery } from "@/api/log";
import 'echarts';
import VueEchart from 'vue-echarts';
const dataRange = ref(1);
const chart: Ref<echarts.ECharts | null> = ref(null);

const props = defineProps({
  id: {
    type: String,
    default: "VisitTrend",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

/** 设置图表  */
const setChartOptions = (data: VisitTrendVO) => {
  if (!chart.value) {
    return;
  }

  const options = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["浏览量(PV)", "IP"],
      bottom: 0,
    },
    grid: {
      left: "1%",
      right: "5%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.dates,
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "浏览量(PV)",
        type: "line",
        data: data.pvList,
        areaStyle: {
          color: "rgba(64, 158, 255, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#409EFF",
        },
        lineStyle: {
          color: "#409EFF",
        },
      },
      {
        name: "IP",
        type: "line",
        data: data.ipList,
        areaStyle: {
          color: "rgba(103, 194, 58, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#67C23A",
        },
        lineStyle: {
          color: "#67C23A",
        },
      },
    ],
  };

  chart.value.setOption(options);
};

/** 计算起止时间范围 */
const calculateDateRange = () => {
  const now = new Date();

  const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  const days = dataRange.value === 1 ? 7 : 30;
  const startDate = new Date(endDate);
  startDate.setDate(startDate.getDate() - days);

  // 手动调整日期为当地时间的 23:59:59
  const adjustDateToLocal = (date: Date) => {
    date.setHours(23, 59, 59, 999);
    return date;
  };

  const adjustedEndDate = adjustDateToLocal(new Date(endDate));
  const adjustedStartDate = adjustDateToLocal(new Date(startDate));
  const formattedStartDate = adjustedStartDate.toISOString().split("T")[0];
  const formattedEndDate = adjustedEndDate.toISOString().split("T")[0];

  return { startDate: formattedStartDate, endDate: formattedEndDate };
};

/** 加载数据 */
const loadData = () => {
  const { startDate, endDate } = calculateDateRange();
  StatsAPI.getVisitTrend({
    startDate,
    endDate,
  } as VisitTrendQuery).then((data) => {
    setChartOptions(data);
  });
};

const handleDateRangeChange = () => {
  loadData();
};

/** 下载图表 */
const handleDownloadChart = () => {
  if (!chart.value) {
    return;
  }

  // 获取画布图表地址信息
  const img = new Image();
  img.src = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1,
    backgroundColor: "#fff",
  });
  // 当图片加载完成后，生成 URL 并下载
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const link = document.createElement("a");
      link.download = `访问趋势.png`;
      link.href = canvas.toDataURL("image/png", 0.9);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };
};

/** 窗口大小变化时，重置图表大小 */
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};
/** 初始化图表  */
onMounted(() => {
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );
  loadData();

  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});

onActivated(() => {
  handleResize();
});
const options = ref({})
options.value = {
  xAxis: {
    type: 'category',
    data: ['后备转种母', '采购', '挑拨转入', '死亡', '淘汰', '销售']
  },
  yAxis: {
    type: 'value'
  },
  title: {
    text: '种母存栏变动',
    left: 'center'
  },
  series: [
    {
      data: [
        25,
        {
          value: 20,
          itemStyle: {
            color: '#a90000'
          }
        },
        30,
        10,
        7,
        15,
      ],
      type: 'bar'
    }
  ]
};
const option2 = ref({})
option2.value = {
  title: {
    text: '种母存栏结构',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '种母存栏结构',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 15, name: '待配种' },
        { value: 8, name: '待首次妊检' },
        { value: 10, name: '待二次妊检' },
        { value: 12, name: '待上产床' },
        { value: 9, name: '待分娩' },
        { value: 15, name: '种母待断奶' },
        { value: 8, name: '妊娠换科' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
const option3 = ref({})
option3.value = {
  title: {
    text: '近30日死淘趋势'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {},

  toolbox: {
    show: true,
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      dataView: { readOnly: false },
      magicType: { type: ['line', 'bar'] },
      restore: {},
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['7/16', '7/17', '7/18', '7/19', '7/20', '7/21', '7/22', '7/23', '7/24', '7/25', '7/26', '7/27', '7/28', '7/29', '7/30',
      '7/31', '8/1', '8/2', '8/3', '8/4', '8/5', '8/6',
      '8/7', '8/8', '8/9', '8/10', '8/11', '8/12']
  },
  yAxis: {
    type: 'value',

  },
  series: [
    {
      name: '死亡数',
      type: 'line',
      data: [1, 3, 2, 0, 3, 2, 1, 2, 4, 2, 5, 2, 3, 2, 2, 2, 5, 2, 1, 1, 2, 2, 3, 2, 2, 2, 2],
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },

    },
    {
      name: '淘汰数',
      type: 'line',
      data: [1, 2, 2, 5, 3, 2, 2, 4, 3, 2, 4, 1, 2, 3, 3, 2, 1, 2, 1, 2, 4, 2, 1, 2, 3, 2, 3, 2],
      markPoint: {
        data: [{ name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 }]
      },
    }
  ]
};
const option4 = ref({})
option4.value = {
  title: {
    text: '近30日存栏趋势'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['7/16', '7/17', '7/18', '7/19', '7/20', '7/21', '7/22', '7/23', '7/24', '7/25', '7/26', '7/27', '7/28', '7/29', '7/30',
        '7/31', '8/1', '8/2', '8/3', '8/4', '8/5', '8/6',
        '8/7', '8/8', '8/9', '8/10', '8/11', '8/12']
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '存栏',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [100, 125, 126, 130, 143, 132, 150, 134, 133, 120, 119, 100, 130, 132, 133, 136, 129, 140, 145, 150, 120, 130, 140, 134, 133, 120, 122]
    },

  ]
};
</script>
<style lang="scss" scoped></style>
